package com.wiim.ui;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Arrays;

import org.json.JSONException;

import com.facebook.FacebookException;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.OnErrorListener;
import com.wiim.common.ConstantValue;
import com.wiim.common.Utilities;
import com.wiim.common.Utils;
import com.wiim.handler.CMCmdHandler;
import com.wiim.interfaceapp.IServiceCommandResult;
import com.wiim.libs.SessionManager;
import com.wiim.model.DanhSachModel;
import com.wiim.model.FaceModel;
import com.wiim.model.UserData;
import com.wiim.nhapnhap.AppGlobal;
import com.wiim.nhapnhap.EgoodApp;
import com.wiim.nhapnhap.MainActivity;
import com.wiim.nhapnhap.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity implements IServiceCommandResult {

	private Button btnLogin;
	private EditText edtEmail, edtPassword;
	private TextView btnLinkToRegisterScreen;
	// private RelativeLayout ll;
	private LoginButton btnSignup;
	private SessionManager session1;
	private GraphUser userfb;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_layout);

		InsControls();
		loginFace();
	}

	public static FaceModel derectionModel = new FaceModel();

	public static FaceModel getFaceModel() {
		if (null == derectionModel)
			derectionModel = new FaceModel();
		return derectionModel;
	}

	private void loginFace() {
		btnSignup.setOnErrorListener(new OnErrorListener() {

			@Override
			public void onError(FacebookException error) {
				Log.i("HAI", "Error " + error.getMessage());
			}
		});
		// set permission list, Don't forget to add email
		btnSignup.setReadPermissions(Arrays.asList("basic_info", "email"));
		// session state call back event
		btnSignup.setSessionStatusCallback(new Session.StatusCallback() {

			@Override
			public void call(Session session, SessionState state, Exception exception) {
				if (session.isOpened()) {
					Log.i("HAI", "Access Token" + session.getAccessToken());
					Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

						@Override
						public void onCompleted(GraphUser user, Response response) {
							if (user != null) {
								Log.i("HAI", "User ID " + user.getId());
								Log.i("HAI", "Email " + user.asMap().get("email"));
								Log.i("HAI", "username " + user.asMap().get("username"));
								final String email = (String) user.asMap().get("email");
								// final String username = (String)
								// user.asMap().get("username");
								// final String userId = user.getId();

								try {
									derectionModel.setData(user, email);
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								Intent i = new Intent(LoginActivity.this, DangKiActivity.class);
								startActivity(i);
							}

						}
					});
				}

			}
		});

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
	}

	String pass;

	private void InsControls() {
		session1 = new SessionManager(LoginActivity.this);
		btnSignup = (LoginButton) findViewById(R.id.btnSignup);
		// ll = (RelativeLayout) findViewById(R.id.ll);
		btnLogin = (Button) findViewById(R.id.btnLogin);
		edtEmail = (EditText) findViewById(R.id.edtEmail);
		edtPassword = (EditText) findViewById(R.id.edtPassword);
		btnLinkToRegisterScreen = (TextView) findViewById(R.id.btnLinkToRegisterScreen);
		
		// edtEmail.setText("b");
		// edtPassword.setText("b");

		// use for SDK android > 3.0
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectNetwork().build());

		GlobalExceptionHandler exceptionHandler = new GlobalExceptionHandler(Thread.getDefaultUncaughtExceptionHandler());
		Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);

		btnLogin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (checkConstraint()) {
					UserData uData = new UserData();
					uData.setUsername(edtEmail.getText().toString().trim());
					pass = edtPassword.getText().toString().trim();
					uData.setPassword(pass);
					uData.setDeviceID(Utils.getDeviceID(LoginActivity.this));
					uData.setAccountType(ConstantValue.AccountType.NATIVE.toString());

					Bundle b = new Bundle();
					b.putSerializable(EgoodApp.REST_OBJECT_PUT, uData);
					AppGlobal.getInstance().startServiceCmd(CMCmdHandler.COMMAND_LOGIN_VALIDATE, LoginActivity.this, new CMCmdHandler(), b, true);
					// changeScreen();
				}
			}
		});

		btnLinkToRegisterScreen.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent i = new Intent(LoginActivity.this, DangKiActivity.class);
				startActivity(i);
				finish();

			}
		});

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			UserData datas = (UserData) extras.getSerializable("USER_DATA");
			if (datas != null) {
				// do stuff
				edtEmail.setText(datas.Username);
			}
		}

	}

	public Boolean checkConstraint() {

		if (this.edtEmail.getText().toString().trim().equalsIgnoreCase("")) {
			return false;
		}
		if (this.edtPassword.getText().toString().trim().equalsIgnoreCase("")) {
			return false;
		}
		return true;
	}

	// @Override
	// public void onBackPressed() {
	// System.exit(0);
	// }

	public static UserData u = new UserData();

	public void processCommandResult(int commandCode, Object resultData) {
		Bundle bResultData = (Bundle) resultData;
		switch (commandCode) {
		case CMCmdHandler.COMMAND_LOGIN_VALIDATE: {
			UserData uData = (UserData) bResultData.getSerializable(EgoodApp.REST_OBJECT_RETURN);

			if (uData.ValidateUserResponse.equalsIgnoreCase(ConstantValue.ValidateUserResponse.SUCCESS.toString())) {
				u.setUsername(uData.Username);
				u.setAccountType(uData.AccountType);
				u.setDeviceID(uData.DeviceID);
				u.setLastLogin(uData.LastLogin);
				u.setPassword(uData.Password);
				u.setUserId(uData.UserId);
				u.Fullname = uData.Fullname;

				u.RewardAmount = uData.RewardAmount == null ? "0" : uData.RewardAmount;
				session1.saveLogin(uData.Username, pass, true);
				changeScreen();
			} else {
				Toast.makeText(this, uData.ValidateUserResponse, Toast.LENGTH_LONG).show();
			}
		}
			break;

		default:
			break;
		}
	}

	public UserData getUserModel() {
		if (u == null) {
			u = new UserData();
		}
		return u;
	}

	private void changeScreen() {
		LoginActivity.this.finish();
		Intent itTab = new Intent().setClass(LoginActivity.this.getApplicationContext(), MainActivity.class);
		// Bundle bundle = new Bundle();
		// bundle.putInt("indexTab", 0);
		// itTab.putExtras(bundle);
		LoginActivity.this.startActivity(itTab);
	}

	private class GlobalExceptionHandler implements UncaughtExceptionHandler {
		// private UncaughtExceptionHandler oldHandler;
		GlobalExceptionHandler(UncaughtExceptionHandler oldHandler) {
			// this.oldHandler = oldHandler;
		}

		@Override
		public void uncaughtException(Thread thread, Throwable throwable) {
			// messageBox(MessageTypes.Info, throwable.getMessage());
			// SpellAppMgr.getInstance().setForegroundNFC(getApplicationContext(),
			// false);
			Log.e("uncaughtException", throwable.getMessage());
		}
	}
}